﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    private Transform target;
    private Vector3 offset;
    private Vector2 velocity;

    private void Update()
    {
        if (target==null && GameObject.FindGameObjectWithTag("Player")!=null)
        {
            target = GameObject.FindGameObjectWithTag("Player").transform;//位置
            offset = target.position - transform.position;//偏移量
        }
    }
    private void FixedUpdate()
    {
        if (target != null)
        {
            //Mathf.SmoothDamp平滑阻尼,游戏中用于做相机的缓冲跟踪和boss直升机跟踪士兵。该函数是Unity3D中Mathf数学运算函数中的一个。
            //平滑缓冲，东西不是僵硬的移动而是做减速缓冲运动到指定位置
            float posX = Mathf.SmoothDamp(transform.position.x,
                target.position.x - offset.x,
                ref velocity.x,
                0.05f);
            float posY = Mathf.SmoothDamp(transform.position.y,
               target.position.y - offset.y,
               ref velocity.y,
               0.05f);

            //解决摄像机抖动
            if (posY>transform.position.y)
            {
                transform.position = new Vector3(posX,posY,transform.position.z);
            }
        }
    }
}
